/**
 * 单词本详情模块
 * 以表格形式展示单词本内容，支持搜索、筛选、分页
 */

class WordbookDetailManager {
    constructor() {
        this.currentWordbook = null;
        this.allWords = [];
        this.filteredWords = [];
        this.currentPage = 1;
        this.pageSize = 100;
        this.searchKeyword = '';
        this.filterCategory = 'all';
        this.filterType = 'all';
        
        // 缓存
        this.cache = new Map();
        
        console.log('📋 单词本详情管理器已加载');
    }

    /**
     * 显示单词本详情
     */
    showDetail(wordbookId) {
        console.log('📖 显示单词本详情:', wordbookId);
        
        // 检查缓存
        if (this.cache.has(wordbookId)) {
            console.log('✅ 使用缓存数据');
            this.currentWordbook = this.cache.get(wordbookId);
        } else {
            const wordbook = window.wordbookManager?.getWordbookById(wordbookId);
            if (!wordbook) {
                alert('单词本不存在');
                return;
            }
            this.currentWordbook = wordbook;
            this.cache.set(wordbookId, wordbook);
        }

        this.allWords = this.currentWordbook.words;
        this.filteredWords = [...this.allWords];
        this.currentPage = 1;

        // 跳转到详情页面
        if (window.app) {
            app.navigateTo('wordbook-detail');
        }

        // 渲染页面
        this.render();
    }

    /**
     * 渲染详情页面
     */
    render() {
        this.renderHeader();
        this.renderStats();
        this.renderFilters();
        this.renderTable();
        this.renderPagination();
        this.bindEvents();
    }

    /**
     * 渲染头部
     */
    renderHeader() {
        const nameElem = document.getElementById('detail-wordbook-name');
        const actionsElem = document.getElementById('detail-actions');
        
        if (nameElem) {
            nameElem.textContent = this.currentWordbook.name;
        }

        if (actionsElem) {
            const canDelete = this.currentWordbook.type === 'custom';
            actionsElem.innerHTML = `
                <button class="btn btn-secondary" onclick="app.startStudy('${this.currentWordbook.id}')">
                    📖 开始学习
                </button>
                <button class="btn btn-secondary" onclick="wordbookManager.exportWordbook('${this.currentWordbook.id}')">
                    💾 导出
                </button>
                ${canDelete ? `
                    <button class="btn btn-danger" onclick="wordbookDetailManager.deleteWordbook()">
                        🗑️ 删除
                    </button>
                ` : ''}
            `;
        }
    }

    /**
     * 渲染统计信息
     */
    renderStats() {
        const statsElem = document.getElementById('detail-stats');
        if (!statsElem) return;

        const wb = this.currentWordbook;
        const progress = this.calculateProgress();

        statsElem.innerHTML = `
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">📝</div>
                    <div class="stat-content">
                        <div class="stat-label">总词汇</div>
                        <div class="stat-value">${wb.wordCount}</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">🏷️</div>
                    <div class="stat-content">
                        <div class="stat-label">分类</div>
                        <div class="stat-value">${wb.category}</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📊</div>
                    <div class="stat-content">
                        <div class="stat-label">学习进度</div>
                        <div class="stat-value">${progress}%</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📅</div>
                    <div class="stat-content">
                        <div class="stat-label">最后学习</div>
                        <div class="stat-value">${wb.stats.lastStudyDate ? this.formatDate(wb.stats.lastStudyDate) : '未学习'}</div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 计算进度
     */
    calculateProgress() {
        if (window.wordbookManager) {
            return wordbookManager.calculateProgress(this.currentWordbook);
        }
        return 0;
    }

    /**
     * 格式化日期
     */
    formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffDays === 0) return '今天';
        if (diffDays === 1) return '昨天';
        if (diffDays < 7) return `${diffDays}天前`;
        return date.toLocaleDateString();
    }

    /**
     * 渲染筛选器
     */
    renderFilters() {
        // 提取所有分类
        const categories = [...new Set(this.allWords.map(w => w.category).filter(c => c))];
        
        const categorySelect = document.getElementById('detail-filter-category');
        if (categorySelect && categories.length > 0) {
            categorySelect.innerHTML = '<option value="all">全部分类</option>' +
                categories.map(c => `<option value="${c}">${c}</option>`).join('');
        }
    }

    /**
     * 渲染表格
     */
    renderTable() {
        const tbody = document.getElementById('wordbook-table-body');
        if (!tbody) return;

        // 应用筛选
        this.applyFilters();

        // 计算分页
        const totalPages = Math.ceil(this.filteredWords.length / this.pageSize);
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = Math.min(startIndex + this.pageSize, this.filteredWords.length);
        const pageWords = this.filteredWords.slice(startIndex, endIndex);

        console.log(`📄 显示第 ${this.currentPage}/${totalPages} 页，共 ${this.filteredWords.length} 个单词`);

        if (pageWords.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="empty-row">
                        <div class="empty-state-small">
                            <p>没有找到符合条件的单词</p>
                        </div>
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = pageWords.map((word, index) => {
            const globalIndex = startIndex + index + 1;
            return this.renderTableRow(word, globalIndex);
        }).join('');
    }

    /**
     * 渲染表格行
     */
    renderTableRow(word, index) {
        const displayWord = word.word.includes(' ') 
            ? this.formatCamelCase(word.word) 
            : word.word;

        const difficulty = word.difficulty ? '⭐'.repeat(parseInt(word.difficulty)) : '-';

        return `
            <tr class="word-row">
                <td class="text-center">${index}</td>
                <td class="word-cell">
                    <code>${displayWord}</code>
                    ${word.pronunciation_mode === 'split' ? '<span class="badge-camel">驼峰</span>' : ''}
                </td>
                <td>${word.translation || '-'}</td>
                <td><span class="category-tag">${word.category || '-'}</span></td>
                <td>${word.type || '-'}</td>
                <td class="code-cell">${word.example_code ? `<code>${this.truncate(word.example_code, 40)}</code>` : '-'}</td>
                <td class="text-center">${difficulty}</td>
                <td class="text-center">
                    <button class="btn-icon-small" onclick="wordbookDetailManager.playWord('${word.word.replace(/'/g, "\\'")}', '${word.pronunciation_mode}')" title="播放发音">
                        🔊
                    </button>
                </td>
            </tr>
        `;
    }

    /**
     * 格式化为驼峰
     */
    formatCamelCase(word) {
        if (word.includes(' ')) {
            const words = word.split(' ');
            return words[0].toLowerCase() + 
                   words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
        }
        return word;
    }

    /**
     * 截断文本
     */
    truncate(text, length) {
        if (!text) return '';
        if (text.length <= length) return text;
        return text.substring(0, length) + '...';
    }

    /**
     * 应用筛选
     */
    applyFilters() {
        this.filteredWords = this.allWords.filter(word => {
            // 搜索关键词
            if (this.searchKeyword) {
                const keyword = this.searchKeyword.toLowerCase();
                const matchWord = word.word.toLowerCase().includes(keyword);
                const matchTranslation = word.translation?.toLowerCase().includes(keyword);
                if (!matchWord && !matchTranslation) {
                    return false;
                }
            }

            // 分类筛选
            if (this.filterCategory !== 'all' && word.category !== this.filterCategory) {
                return false;
            }

            // 类型筛选
            if (this.filterType !== 'all' && word.type !== this.filterType) {
                return false;
            }

            return true;
        });

        // 重置到第一页
        this.currentPage = 1;
    }

    /**
     * 渲染分页
     */
    renderPagination() {
        const paginationElem = document.getElementById('detail-pagination');
        if (!paginationElem) return;

        const totalPages = Math.ceil(this.filteredWords.length / this.pageSize);
        
        if (totalPages <= 1) {
            paginationElem.innerHTML = `
                <div class="pagination-info">
                    共 ${this.filteredWords.length} 个单词
                </div>
            `;
            return;
        }

        // 生成页码按钮
        let pageButtons = '';
        
        // 上一页
        pageButtons += `
            <button class="page-btn" ${this.currentPage === 1 ? 'disabled' : ''} 
                    onclick="wordbookDetailManager.goToPage(${this.currentPage - 1})">
                ←
            </button>
        `;

        // 页码按钮（智能显示）
        const showPages = this.getPageNumbers(this.currentPage, totalPages);
        showPages.forEach(page => {
            if (page === '...') {
                pageButtons += `<span class="page-ellipsis">...</span>`;
            } else {
                pageButtons += `
                    <button class="page-btn ${page === this.currentPage ? 'active' : ''}" 
                            onclick="wordbookDetailManager.goToPage(${page})">
                        ${page}
                    </button>
                `;
            }
        });

        // 下一页
        pageButtons += `
            <button class="page-btn" ${this.currentPage === totalPages ? 'disabled' : ''} 
                    onclick="wordbookDetailManager.goToPage(${this.currentPage + 1})">
                →
            </button>
        `;

        paginationElem.innerHTML = `
            <div class="pagination-info">
                第 ${this.currentPage}/${totalPages} 页，共 ${this.filteredWords.length} 个单词
            </div>
            <div class="pagination-buttons">
                ${pageButtons}
            </div>
        `;
    }

    /**
     * 获取要显示的页码
     */
    getPageNumbers(current, total) {
        const pages = [];
        
        if (total <= 7) {
            for (let i = 1; i <= total; i++) {
                pages.push(i);
            }
        } else {
            pages.push(1);
            
            if (current > 3) {
                pages.push('...');
            }
            
            for (let i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) {
                if (!pages.includes(i)) {
                    pages.push(i);
                }
            }
            
            if (current < total - 2) {
                pages.push('...');
            }
            
            if (!pages.includes(total)) {
                pages.push(total);
            }
        }
        
        return pages;
    }

    /**
     * 跳转到指定页
     */
    goToPage(page) {
        const totalPages = Math.ceil(this.filteredWords.length / this.pageSize);
        if (page < 1 || page > totalPages) return;
        
        this.currentPage = page;
        this.renderTable();
        this.renderPagination();

        // 滚动到表格顶部
        const table = document.querySelector('.wordbook-table-container');
        if (table) {
            table.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 搜索
        const searchInput = document.getElementById('detail-search');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.searchKeyword = e.target.value;
                this.renderTable();
                this.renderPagination();
            });
        }

        // 分类筛选
        const categorySelect = document.getElementById('detail-filter-category');
        if (categorySelect) {
            categorySelect.addEventListener('change', (e) => {
                this.filterCategory = e.target.value;
                this.renderTable();
                this.renderPagination();
            });
        }

        // 类型筛选
        const typeSelect = document.getElementById('detail-filter-type');
        if (typeSelect) {
            typeSelect.addEventListener('change', (e) => {
                this.filterType = e.target.value;
                this.renderTable();
                this.renderPagination();
            });
        }

        // 每页数量
        const pageSizeSelect = document.getElementById('detail-page-size');
        if (pageSizeSelect) {
            pageSizeSelect.addEventListener('change', (e) => {
                this.pageSize = parseInt(e.target.value);
                this.currentPage = 1;
                this.renderTable();
                this.renderPagination();
            });
        }
    }

    /**
     * 播放单词
     */
    playWord(word, mode) {
        if (!window.speechManager) return;

        if (mode === 'split') {
            const displayWord = this.formatCamelCase(word);
            speechManager.speakCamelCase(displayWord);
        } else {
            speechManager.speak(word);
        }
    }

    /**
     * 删除单词本
     */
    deleteWordbook() {
        if (!this.currentWordbook) return;

        if (confirm(`确定要删除单词本"${this.currentWordbook.name}"吗？\n\n此操作不可恢复！`)) {
            const success = window.wordbookManager?.deleteWordbook(this.currentWordbook.id);
            if (success) {
                // 清除缓存
                this.cache.delete(this.currentWordbook.id);
                
                // 返回单词本管理页面
                if (window.app) {
                    app.navigateTo('wordbooks');
                }
                
                alert('删除成功！');
            }
        }
    }

    /**
     * 清除缓存
     */
    clearCache() {
        this.cache.clear();
        console.log('🗑️ 缓存已清除');
    }

    /**
     * 获取缓存大小（估算，单位：MB）
     */
    getCacheSize() {
        let totalSize = 0;
        this.cache.forEach(wordbook => {
            const jsonString = JSON.stringify(wordbook);
            totalSize += jsonString.length;
        });
        return (totalSize / 1024 / 1024).toFixed(2);
    }
}

// 全局实例
const wordbookDetailManager = new WordbookDetailManager();
window.wordbookDetailManager = wordbookDetailManager;

